#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime

from gm.api import *

from web.config.commodity_future_date_contract_data_config import CommodityFutureDateContractDataConfig
from web.config.commodity_future_hour_data_config import CommodityFutureHourDataConfig
from web.config.myquant_config import MyQuantConfig
from web.models import CommodityFutureHourData
from web.task.base_task import BaseTask
from web.manager.log_manager import LogManager

Logger = LogManager.get_logger(__name__)

"""
通过掘金量化，下载商品期货1小时级别数据
"""


class MyQuantDownloadCommodityFutureHourDataTask(BaseTask):

    def download_commodity_future_hour_data(self):
        """
        通过掘金量化，下载商品期货1小时级别数据
        """
        # 掘金终端需要打开，接口取数是通过网络请求的方式
        # 设置token，可在用户-密钥管理里查看获取已有token ID
        set_token(MyQuantConfig.MyQuant_Token)

        # 查询所有期货信息
        commodity_future_info_queryset = self.commodity_future_info_service.find_all()
        # 查询code列表
        code_list = self.commodity_future_hour_data_service.distinct_code()
        if commodity_future_info_queryset is not None and len(commodity_future_info_queryset):
            for commodity_future_info in commodity_future_info_queryset:
                # 判断数据是否已经存在
                # if commodity_future_info.code in code_list:
                #     Logger.warn(
                #         "code为[" + commodity_future_info.code + "]，name为[" + commodity_future_info.name + "]的数据已经存在")
                #     continue

                # 查询某个期货的最大的和最小的transaction_date
                # max_transaction_date, min_transaction_date = self.commodity_future_date_data_service.find_max_and_min_transaction_date_by_code(
                #     commodity_future_info.code)
                # if max_transaction_date is None or min_transaction_date is None:
                #     continue

                # 根据code，合并交易所code和期货code
                concatenate_code = self.commodity_future_info_service.concatenate_commodity_future_exchange_code_and_commodity_future_info_code_by_commodity_future_info_code(
                    commodity_future_info.code)
                if concatenate_code is not None:
                    Logger.info(
                        "开始查询期货[" + commodity_future_info.code + "]在日期[" + CommodityFutureHourDataConfig.Commodity_Future_Hour_Data_Basic_Data_Begin_Time + "]和["
                        + CommodityFutureHourDataConfig.Commodity_Future_Hour_Data_Basic_Data_End_Time + "]之间的数据")

                    try:
                        history_dataframe = history(symbol=concatenate_code,
                                                    frequency=CommodityFutureHourDataConfig.Commodity_Future_Hour_Data_Basic_Data_Frequency,
                                                    start_time=CommodityFutureHourDataConfig.Commodity_Future_Hour_Data_Basic_Data_Begin_Time,
                                                    end_time=CommodityFutureHourDataConfig.Commodity_Future_Hour_Data_Basic_Data_End_Time,
                                                    fields=CommodityFutureHourDataConfig.Commodity_Future_Hour_Data_Basic_Data_Fields,
                                                    adjust=ADJUST_PREV, df=True)
                    except GmError as e:
                        Logger.error(
                            "获取期货[" + commodity_future_info.code + " " + commodity_future_info.name + "]的数据时报错：")
                        print(e)
                        continue

                    if history_dataframe is not None and len(history_dataframe):
                        commodity_future_hour_data_list = list()
                        for index, row in history_dataframe.iterrows():
                            commodity_future_hour_data = CommodityFutureHourData()
                            commodity_future_hour_data.name = commodity_future_info.name
                            commodity_future_hour_data.code = commodity_future_info.code
                            commodity_future_hour_data.open_price = row["open"]
                            commodity_future_hour_data.highest_price = row["high"]
                            commodity_future_hour_data.lowest_price = row["low"]
                            commodity_future_hour_data.close_price = row["close"]
                            commodity_future_hour_data.turnover = row["volume"]
                            commodity_future_hour_data.volume = row["amount"]
                            commodity_future_hour_data.open_interest = row["position"]
                            commodity_future_hour_data.begin_time = datetime.fromtimestamp(row["bob"].timestamp())
                            commodity_future_hour_data.end_time = datetime.fromtimestamp(row["eob"].timestamp())
                            commodity_future_hour_data_list.append(commodity_future_hour_data)
                        self.commodity_future_hour_data_service.save_commodity_future_hour_data_list(
                            commodity_future_hour_data_list)
                    else:
                        Logger.warn(
                            "期货[" + commodity_future_info.code + "]在日期[" + CommodityFutureHourDataConfig.Commodity_Future_Hour_Data_Basic_Data_Begin_Time + "]和["
                            + CommodityFutureHourDataConfig.Commodity_Future_Hour_Data_Basic_Data_End_Time + "]之间没有数据")
                else:
                    Logger.warn("期货[" + commodity_future_info.code + "]没有可以合并的code")

        Logger.info("方法download_commodity_future_hour_data执行结束")
